<!-- 新增/编辑 组织机构 -->
<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    @cancel="handleCancel"
    :mask-closable="false"
    @before-ok="handleBeforeOk"
    width="700px"
    unmount-on-close
  >
    <page-form :model="form" layout="vertical" div="true" class="page-form" ref="formRef">
      <!-- 编辑 -->
      <div v-if="pagetype == 'edit'" class="dis-wrap">
        <page-form-item field="parentId" label="上级机构" required size="1" disabled>
          <a-tree-select :data="treeData" v-model="form.parentId" placeholder="请选择" />
        </page-form-item>
      </div>
      <!-- 添加 -->
      <div v-else class="dis-wrap">
        <page-form-item field="id" label="上级机构" required size="1">
          <a-tree-select :data="treeData" v-model="form.id" placeholder="请选择" />
        </page-form-item>
      </div>
      <page-form-item
        field="orgType"
        label="机构类型"
        required
        size="1/2"
        :disabled="pagetype == 'edit' ? true : false"
        :rules="[{ required: true, message: '请选择机构类型' }]"
      >
        <a-select placeholder="请选择" v-model="form.orgType" @change="orgTypeChange">
          <a-option v-for="(item, index) of orgTypeEnum" :key="index" :value="item.key" :label="item.label">{{ item.label }}</a-option>
        </a-select>
      </page-form-item>
      <page-form-item field="orgName" label="机构名称" required size="1/2" :rules="[{ required: true, message: '请填写机构名称' }]">
        <i-input placeholder="请输入" v-model="form.orgName" :max-length="50" />
      </page-form-item>
      <div v-if="form.orgType == 3" class="dis-contents">
        <page-form-item field="latitude" label="门店坐标" required size="1/2" :rules="[{ required: true, message: '请选择门店坐标' }]">
          <a-input placeholder="请选择" v-model="form.lnglat" readonly @click="siteCoordinatesClickFn" />
        </page-form-item>
      </div>
      <div v-if="form.orgType == 3" class="dis-contents">
        <page-form-item field="cityCode" label="城市" required size="1/2" :rules="[{ required: true, message: '请选择城市' }]">
          <remote-select v-model="form.cityCode" type="area_city" @change="cityChange" />
        </page-form-item>
      </div>
      <div v-if="form.orgType == 3" class="dis-contents">
        <page-form-item field="districtCode" label="区县" size="1/2">
          <remote-select
            v-model="form.districtCode"
            :params="{
              parentCode: form.cityCode,
            }"
            :mustParentShow="!form.cityCode"
            mustParentTip="请先选择城市"
            type="area_area"
          />
        </page-form-item>
      </div>
      <div v-if="form.orgType == 3" class="dis-wrap">
        <page-form-item
          field="address"
          label="机构地址"
          required
          size="1"
          :rules="{
            required: form.orgType == 3 ? true : false,
            message: '请选择机构地址',
            trigger: 'change',
          }"
        >
          <i-input placeholder="请填写" v-model="form.address" />
        </page-form-item>
      </div>
      <div v-else class="dis-wrap">
        <page-form-item field="address" label="机构地址" size="1">
          <i-input placeholder="请填写" v-model="form.address" />
        </page-form-item>
      </div>
      <div v-if="form.orgType == 3" class="dis-contents">
        <page-form-item field="siteCarPark" label="门店车场" size="1/2" style="position: relative">
          <i-input placeholder="请输入" style="position: relative" v-model="form.siteCarPark" />
          <div class="operate-list">
            <a-button class="operate-btn" type="primary" @click="copyAddress">同机构地址</a-button>
          </div>
        </page-form-item>
      </div>
      <page-form-item
        field="authOrgIds"
        label="机构权限"
        size="1"
        :required="pagetype == 'edit' ? true : false"
        :rules="[{ required: pagetype == 'edit' ? true : false, message: '请选择机构权限' }]"
      >
        <a-tree-select
          :data="authList"
          tree-check-strictly
          treeCheckable
          :tree-checked-strategy="'all'"
          v-model="form.authOrgIds"
          multiple
          placeholder="请选择"
        >
          <template #header>
            <div style="padding: 6px 12px">
              <a-checkbox :default-checked="allchoose" @change="allChange">全选</a-checkbox>
            </div>
          </template>
        </a-tree-select>
      </page-form-item>
    </page-form>
  </a-modal>
  <!-- 坐标选择 -->
  <lnglat-picker-modal ref="lnglatPickerModalRef" @change="pointChangeFn" />
</template>

<script setup>
  import { getOrgPageData, getOrgDetail, findByNameAndParent, orgAdd, orgEdit, selectAuthList } from '@/api/organization/organization'
  import { ref, onMounted, watch } from 'vue'
  // import { Message } from '@arco-design/web-vue'

  const visible = ref(false)
  const form = ref({
    id: '', //编辑id
    orgName: '', //机构名称
    parentId: '',
    orgType: '', //机构类型
    address: '', //地址
    authOrgIds: [], //机构权限ids
    excludeOrgIds: [], //排除的机构ids
    latitude: '',
    longitude: '',
    cityCode: '',
    districtCode: '', //区编号
    siteCarPark: '', //门店车场
    sort: '', //排序(同一父节点下同一层级机构排序)
    lnglat: '',
  })

  // 重置form
  const resetForm = () => {
    form.value = {
      id: '',
      orgName: '',
      parentId: '',
      orgType: '',
      address: '',
      authOrgIds: [],
      excludeOrgIds: [],
      latitude: '',
      longitude: '',
      cityCode: '',
      districtCode: '',
      siteCarPark: '',
      sort: '',
      lnglat: '',
    }
  }

  // const lnglat = ref(null)

  const title = ref('添加机构')
  const treeData = ref([])
  const orgid = ref(null)
  const pagetype = ref(false)
  const handleClick = (nodeData, type, tree) => {
    getSelectAuthList()
    getCity()
    pagetype.value = type
    if (tree) {
      treeData.value = tree
    }
    orgid.value = nodeData.key
    form.value.id = orgid.value.toString()
    form.value.parentId = nodeData.parentId.toString()
    if (type == 'edit') {
      title.value = '编辑机构'
      orgDetail(orgid.value.toString())
    } else {
      title.value = '添加机构'
    }
    visible.value = true
  }

  // 权限列表
  const authList = ref([]) //权限列表
  const oldDataTree = ref([]) //未处理的树数据
  const getSelectAuthList = () => {
    selectAuthList().then((res) => {
      oldDataTree.value = res.result
      const authTree = res.result.map((e) => {
        e.key = e.id
        e.title = e.orgName
        e.value = e.id
        e.label = e.orgName
        e.children = [] //创建子级
        return e
      })
      authList.value = setTreeData(authTree)
    })
  }

  // 表结构转化为树结构
  const setTreeData = (arr) => {
    // 删除所有的children,以防止多次调用
    arr.forEach(function (item) {
      delete item.children
    })
    let map = {} //构建map
    arr.forEach((i) => {
      map[i.id] = i //构建以id为键 当前数据为值
    })
    let treeData = []
    arr.forEach((child) => {
      const mapItem = map[child.parentId] //判断当前数据的parentId是否存在map中
      if (mapItem) {
        //存在则表示当前数据不是最顶层的数据
        //注意： 这里的map中的数据是引用了arr的它的指向还是arr,当mapItem改变时arr也会改变，踩坑点
        ;(mapItem.children || (mapItem.children = [])).push(child) //这里判断mapItem中是否存在child
      } else {
        //不存在则是顶层数据
        child.top = true
        treeData.push(child)
      }
    })
    return treeData
  }

  // 权限全选
  const allchoose = ref(false)
  const allChange = (e) => {
    if (e == true) {
      form.value.authOrgIds = []
      oldDataTree.value.forEach((i) => {
        form.value.authOrgIds.push(i.id)
      })
    } else {
      form.value.authOrgIds = []
    }
  }

  const formRef = ref()
  const validateFn = () => {
    return new Promise((resolve, reject) => {
      formRef.value.validate((error) => {
        if (error) {
          console.log(error)
          reject()
        } else {
          resolve()
        }
      })
    })
  }

  const handleBeforeOk = (done) => {
    return new Promise((resolve, reject) => {
      validateFn()
        .then(() => {
          console.log('验证通过')
          var params = {
            ...form.value,
          }
          if (pagetype.value == 'edit') {
            console.log(params)
            orgEdit(params)
              .then((res) => {
                console.log(res)
                // Message.success(res.message)
                formRef.value.clearValidate()
                resetPage()
                done()
              })
              .catch(() => {
                // Message.error('保存失败')
                reject()
              })
          } else {
            params.parentId = params.id
            delete params.id
            console.log(params)
            orgAdd(params)
              .then((res) => {
                console.log(res)
                // Message.success(res.message)
                formRef.value.clearValidate()
                resetPage()
                done()
                resolve()
              })
              .catch(() => {
                // Message.error('保存失败')
                reject()
              })
          }
        })
        .catch(() => {
          reject()
        })
    })
  }

  // 回传刷新列表
  const emit = defineEmits(['orgOperate', 'reset'])
  const resetPage = () => {
    console.log('编辑结束', form.value.id)
    visible.value = false
    emit('reset', form.value.id)
    resetForm()
  }

  const handleCancel = () => {
    visible.value = false
    formRef.value.clearValidate()
    resetForm()
  }

  const orgTypeEnum = ref([]) //机构类型
  const getPageData = () => {
    getOrgPageData().then((res) => {
      const orgTypes = res.result.orgTypeEnum.map((e) => {
        e.key = e.value
        e.label = e.name
        return e
      })
      orgTypeEnum.value = orgTypes
    })
  }

  // const orgDetailData = ref(null) //机构详情
  const orgDetail = (id) => {
    getOrgDetail({ id: id }).then((res) => {
      // console.log('form', form)
      res.result.id = res.result.id.toString()
      res.result.parentId = res.result.parentId.toString()
      res.result.orgType = res.result.orgType.toString()
      form.value = res.result //
      form.value.lnglat = form.value.latitude && form.value.longitude ? form.value.longitude + ',' + form.value.latitude : ''
      console.log('form', form.value)
      // 有城市的话，获取区县
      if (form.value.cityCode) {
        getCounty(form.value.cityCode.toString())
      }
    })
  }

  const cityList = ref(null) //cityList
  const getCity = () => {
    findByNameAndParent({ parentCode: '' }).then((res) => {
      cityList.value = res.result
    })
  }
  // 上级获取下级区县
  const cityCode = ref()
  // const cityChange = (e) => {
  //   cityCode.value = e.toString()
  //   getCounty(cityCode.value.toString())
  // }
  // 城市发生改变 补充省份 code
  const cityChange = (value, option) => {
    // form.value.cityCode = option?.parentCode || undefined
    // form.value.districtCode = undefined
    form.value.provinceCode = option?.parentCode || undefined
    form.value.districtCode = undefined
  }
  const countyList = ref(null) //区县
  const getCounty = (cityCode) => {
    findByNameAndParent({ parentCode: cityCode }).then((res) => {
      countyList.value = res.result
    })
  }

  //切换城市，重置区县
  watch(cityCode, () => {
    form.value.districtCode = ''
  })

  const lnglatPickerModalRef = ref(null)
  const siteCoordinatesClickFn = () => {
    lnglatPickerModalRef.value.open(form.value.lnglat)
    formRef.value.clearValidate()
  }
  // 坐标选择
  const pointChangeFn = (lnglat, option) => {
    console.log('选中的地图点坐标1', lnglat)
    console.log('选中的地图点坐标2', option)
    form.value.lnglat = lnglat.toString()
    // lnglat.value = lnglats
    form.value.longitude = lnglat[0]
    form.value.latitude = lnglat[1]
    if (option) {
      const adcode = option.addressComponent.adcode
      form.value.address = option.formattedAddress
      form.value.cityCode = String(parseInt(adcode / 100) * 100)
      form.value.districtCode = adcode
      // console.log(form.value.cityCode)
      // getCounty(form.value.cityCode.toString())
    }
  }

  // 机构地址复制
  const copyAddress = () => {
    form.value.siteCarPark = form.value.address
  }

  defineExpose({
    handleClick,
  })

  // mounted 调用接口
  onMounted(() => {
    getPageData(), getCity(), getSelectAuthList(), resetForm()
  })
</script>

<style lang="less" scoped>
  .page-form {
    margin: 0;
    flex-flow: row wrap;
    max-height: 500px;
    // padding: 0 60px;
    :deep(.arco-row) {
      margin-left: 0 !important;
      margin-right: 0 !important;
    }
    :deep(.arco-modal-body) {
      padding: 10px 80px !important;
    }
    :deep(.arco-col) {
      padding: 0 10px !important;
    }
  }
  .operate-list {
    position: absolute;
    left: calc(100% + 16px);
  }
  .operate-btn + .operate-btn {
    margin-left: 16px;
  }
  .dis-contents {
    display: contents;
  }
  .dis-wrap {
    width: 100%;
  }
</style>
